<!--
 @description
 @fileName editor.vue
 @author zengqiongying
 @created 2021/12/28 16:08:18
-->
<template>
  <div class="full-page">
    <div class="qup-page-header bread-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item><span class="btn-green">富文本编辑器Demo</span></el-breadcrumb-item>
        <el-breadcrumb-item>指定高度</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini">返回</el-button>
      </div>
    </div>
    <div class="bottom-bar-container">
      <div class="word-count">正文字数：<span>{{ contentCount }}</span></div>
      <div>
        <el-button size="mini" type="primary" @click="handleSave(0)">保存</el-button>
        <el-button size="mini" @click="handlePreview">预览</el-button>
        <el-button size="mini" @click="handleSave(1)">发布</el-button>
      </div>
    </div>

    <div class="page-full-content">      
      <el-form ref="refForm" :rules="formRules" :model="formData" label-width="120px" size="small" :show-message="true">
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="title" class="c-form-title" size="small">
              <el-input v-model="formData.title" maxlength="64" placeholder="请在这里输入标题" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="作者" prop="writer" size="mini">
              <el-input v-model="formData.writer" maxlength="12" placeholder="请输入作者" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" size="mini" label-width="100px">          
              
                <div slot="toolbar" class="custom-editor-tool">
                  <el-button plain size="mini" @click.stop="openPicStock('picture')">插入图片</el-button>
                  <el-button plain size="mini" @click.stop="openPicStock('video')">插入视频</el-button>
                  <el-button plain size="mini" @click.stop="openPicStock('audio')">插入音频</el-button>
                  <el-button plain size="mini" @click.stop="openPicStock('file')">上传附件</el-button>
                </div>        
                <QupTinyEditor
                    ref="editor"
                    v-model="htmlContent"
                    base-url="http://localhost:9528/qup-template/po-content/"
                    file-prefix="http://file.quanyou.com.cn/"
                    upload-res-field="enclosurePath"
                    upload-url="/ads-admin/api/v1/adsEnclosureInfo/uploadFile"
                    :custom-buttons="[]"
                    :editor-config="{
                      statusbar:true,
                      inline: false, // 内联
                      // 沉浸式
                      /*
                      plugins: [ 'quickbars' ],
                      toolbar: false,
                      menubar: false,
                      inline: true,
                      quickbars_selection_toolbar: 'bold italic | quicklink h2 h3 blockquote'
                      */
                    }"
                  />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="摘要" prop="abs">
              <el-input
                v-model="formData.abs"
                type="textarea"
                row="6"
                maxlength="120"
                placeholder="选填，摘要可以帮助读者快速了解文章内容，如不填写则默认抓取正文前60个字。"
                show-word-limit
                resize="none"
                class="c-form-summary"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定时推送">
              <div class="c-opt-date">
                <el-switch
                  v-model="formData.isPush"
                  active-color="#13ce66"
                  inactive-color="#999999"
                  :active-value="1"
                  :inactive-value="0"
                />
                <el-date-picker
                  v-if="formData.isPush"
                  v-model="formData.releaseTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                  size="mini"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定时失效">
              <div class="c-opt-date">
                <el-switch
                  v-model="formData.isInvalid"
                  active-color="#13ce66"
                  inactive-color="#999999"
                  :active-value="1"
                  :inactive-value="0"
                />
                <el-date-picker
                  v-if="formData.isInvalid"
                  v-model="formData.invalidTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                  size="mini"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内容分类" prop="categoryCode">
              <el-select v-model="formData.categoryCode" placeholder="请选择">
                <el-option label="分类1" :value="1"/>
                <el-option label="分类2" :value="2"/>
                <el-option label="分类3" :value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="选择推送门户" prop="portalCodes">
              <el-select v-model="formData.portalCodes" placeholder="请选择">
                <el-option label="门户1" :value="1"/>
                <el-option label="门户2" :value="2"/>
                <el-option label="门户3" :value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属内容号:" prop="contentId">
              <el-select v-model="formData.contentId" placeholder="请选择">
                <el-option label="内容号1" :value="1"/>
                <el-option label="内容号2" :value="2"/>
                <el-option label="内容号3" :value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
  </div>
</template>

<script>
// 过滤掉富文本里面包含的html标签和空格符等东西的方法
const fiterHtml = (content) => {
  if (!content) return ''
  content = content.replace(/(\n)/g, '') // 去掉换行
  content = content.replace(/(\t)/g, '') // 去掉换行
  content = content.replace(/(\r)/g, '')
  content = content.replace(/<\/?[^>]*>/g, '') // 去掉标签
  content = content.replace(/\s*/g, '')
  content = content.replace(/ /ig, ' ') // 去掉
  content = content.replace(/<\/?(img|a)[^>]*>/gi, '') // 去掉图片和a标签
  content = content.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/g, '') // 过滤视频
  content = content.replace(/<audio [^>]*src=['"]([^'"]+)[^>]*>/g, '') // 过滤音频
  content = content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, '').replace(/&nbsp;/ig, '') //
  return content
}
export default {
  name: '',
  components: {},
  filters: {},
  mixins: [],
  data() {
    return {
      customConfig: {
        showImgMenu: true, // 是否显示图片
        showMenuVideo: false, //是否显示上传视频
        uploadImgServer: `http://qup2dev.quanyou.com.cn/mcenter/api/v1/file/upload`, // 上传图片api地址
        uploadFileName: 'multipartFile', // 上传图片入参
        customImgField:'fileUrl', // 上传图片成功返回图片地址字段名

        uploadVideoServer: `http://qup2dev.quanyou.com.cn/mcenter/api/v1/file/upload`, // 上传视频服务器地址
        uploadVideoName: 'file', // 上传视频入参
        customVideoField:'fileUrl',// 上传视频成功返回视频地址字段名
      },
      htmlContent: '',
      insertType: '', // 插入素材类型： picture/video/audio/file
      attachData: [],
      formData: {
        title: '',
        writer: '',
        coverImgUrl: '',
        abs: '',
        isPush: 0,
        releaseTime: '',
        isInvalid: 0,
        invalidTime: '',
        categoryCode: '',
        portalCodes: '',
        isMsg: '',
        domainCode: '',
        domainName: '',
        contentId: '',
        contentName: '',
        isTop: 0
      },
      formRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        writer: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        categoryCode: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        portalCodes: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        contentId: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }
    }
  },

  computed: {
    defaultSummary() {
      return fiterHtml(this.htmlContent)
    },
    contentCount() {
      let count = 0
      count = this.defaultSummary.length
      return count
    }
  },

  created() {},
  methods: {
    /**
     * 打开图库选择框
     */
    openPicStock(type) {
      this.insertType = type || ''
      console.log('此处执行打开图库的操作添加素材',type)
      // 调用自定义组件选中素材后，执行 handleInsert 插入到富文本编辑框中
    },
    // 插入内容到富文本编辑框
    handleInsert(lists, type) {
      // 首先获取富文本编辑器的实例
      if (type === 'file') {
        if (this.attachData.length === 0) {
          this.attachData = lists.map(v => {
            return {
              attachUrl: v.fileUrl,
              attachName: v.fileName
            }
          })
        }
        lists.forEach(item => {
          const index = this.attachData.findIndex(v => v.attachUrl === item.fileUrl)
          if (index === -1) {
            this.attachData.push({
              attachUrl: item.fileUrl,
              attachName: item.fileName
            })
          }
        })
        return
      }
      const qupEditor = this.$refs.qupEditor
      for (let i = 0; i < lists.length; i++) {
        const obj = lists[i]
        const url = this.formatImageUrl(obj.fileUrl || '')
        qupEditor.insertContent(type, `${url}`)
      }
    },
    // 删除附件
    handleDelAtt(index) {
      this.attachData.splice(index, 1)
    },
    //获取富文本中的图片
    getImgsFromHtml(content){
      if (!content) return []
      const imgs = []
      content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function(match, capture) {
        imgs.push(capture)
      })
      return imgs
    },
    // 预览
    handlePreview() {
      console.log('预览',this.htmlContent)
    },
    // 保存
    handleSave(isPublish) {
      if (!this.formData.title) {
        this.$message.warning('请输入标题')
        return
      }
      /* if (!this.formData.writer) {
        this.$message.warning('请输入作者')
        return
      } */
      const defaultCover = this.getImgsFromHtml(this.htmlContent)
      if (this.contentCount === 0 && defaultCover.length === 0) {
        this.$message.warning('请输入内容')
        return
      }
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          console.log('保存表单数据',this.formData,this.htmlContent)
        }
      })
    },
    
  }
}

</script>
<style lang='scss' scoped>
.full-page{
  position: relative;
  height: 100vh;
}
.qup-page-header{
  position: fixed;
  left: 12px;
  top: 0;
  right:12px;
  z-index: 99;
  background: #ffffff;
  padding-top: 12px !important;
  display: flex;
  justify-content: space-between;
}
.page-full-content{
  position: relative;
  min-height: 100%;
  padding-top:39px;
  padding-bottom: 68px;
}
.bottom-bar-container{
  position: fixed;
  left: 12px;
  right: 12px;
  bottom: 0;
  z-index: 99;
  box-shadow: 0 2px 8px rgba(115,115,115,.3);
  background: #fff;
  padding: 20px 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .word-count{
    color: #333;
  }
}

.custom-editor-tool{
  // max-width: 930px;
  // margin:  0 auto;
  padding: 10px;
}

.c-basic-form{
  padding-top: 10px;
  /deep/.el-input__inner{
    border-color: #fff;
    font-size:14px;
    &:focus{
      border-color:#3DC094;
    }
  }
  
  /deep/.el-form-item__error{
    padding-left: 12px;
  }

  .c-form-title{
    /deep/ .el-input--small .el-input__inner{
      font-weight: bold;
      font-size: 18px;
      padding:  0 10px;
    }
  }
}
.c-content-form{
  padding-top: 10px;
}
</style>
